package cn.ilikes.tools.nosql.jpa.query.sql.element;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.persistence.Parameter;

import cn.ilikes.tools.nosql.jpa.SysConfigs;
import cn.ilikes.tools.nosql.jpa.clients.indexs.IClientIndex;
import cn.ilikes.tools.nosql.jpa.clients.indexs.units.LuceneQueryUtils;
import cn.ilikes.tools.nosql.jpa.clients.indexs.units.LuceneUtils;
import cn.ilikes.tools.nosql.jpa.metadatas.EntityMetaData;
import cn.ilikes.tools.nosql.jpa.metadatas.elements.EntityFields;
import cn.ilikes.tools.nosql.jpa.metadatas.elements.Relation;
import cn.ilikes.tools.nosql.jpa.query.JPASQLQueryRunTimeException;
import cn.ilikes.tools.nosql.jpa.query.iquerys.IQuery;
import cn.ilikes.tools.nosql.jpa.query.pasers.ParentWhereList;
import cn.ilikes.tools.nosql.jpa.query.sql.element.Properties.Between;
import cn.ilikes.tools.nosql.jpa.query.sql.element.WhereList.ListType;
import cn.ilikes.tools.nosql.jpa.unitls.JPAUtils;

public class SQLTable {

	private String tableName;

	private String aliasName;

	private WhereList whereList;

	private List<GroupBy> groupBy = new ArrayList<GroupBy>();

	public SQLTable() {

	}

	public List<GroupBy> getGroupBy() {
		return groupBy;
	}

	public void setGroupBy(List<GroupBy> groupBy) {
		this.groupBy = groupBy;
	}

	public String getTableName() {
		return tableName;
	}

	public String getAliasName() {
		return aliasName;
	}

	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

	public void setAliasName(String aliasName) {
		this.aliasName = aliasName;
	}

	public WhereList getWhereList() {
		return whereList;
	}

	public void setWhereList(WhereList whereList) {
		this.whereList = whereList;
	}

	@Override
	public String toString() {
		return "KuTable [tableName=" + tableName + ", aliasName=" + aliasName + ", whereList=" + toWhere() + "]";
	}

	public String toWhere() {
		StringBuffer result = new StringBuffer();
		result.append("->[ ");
		printWhereList(whereList, result);
		result.append(" ]<-");
		return result.toString();
	}

	private void printWhereList(Element element, StringBuffer result) {

		if (element instanceof WhereList) {
			if (element instanceof ParentWhereList) {
				result.append("(");
			}
			WhereList whereList = (WhereList) element;
			printWhereList(whereList.getLeftList(), result);
			if (!whereList.getListType().equals(ListType.parent))
				result.append(" " + whereList.getListType() + " ");
			printWhereList(whereList.getRightList(), result);
			if (element instanceof ParentWhereList) {
				result.append(")");
			}
		}
		if (element instanceof Properties) {
			Object value = ((Properties) element).getValue();
			if (value instanceof Between) {
				Between element_ = (Between) value;
				result.append(" " + element_.getStart() + " to  " + element_.getEnd() + " ");
			} else {
				result.append(" " + ((Properties) element).getValue() + " ");
			}

		}
	}
}
